<!--
 * @Author: baozhoutao@steedos.com
 * @Date: 2022-06-02 17:45:15
 * @LastEditors: 殷亮辉 yinlianghui@hotoa.com
 * @LastEditTime: 2024-03-14 18:48:28
 * @Description: 
-->
<html>
  <head>
    <script src="/unpkg.com/@steedos-builder/fiddle@0.0.5/dist/builder-fiddle.umd.js"></script>
    <script src="/unpkg.com/axios@0.26.1/dist/axios.min.js"></script>
    <script src="https://unpkg.steedos.cn/flowbite@2.3.0/dist/flowbite.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>

  <body>
    <!-- Main modal -->
    <div id="fieldLayoutModal" tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
      <div class="relative p-4 w-full max-w-2xl max-h-full">
          <!-- Modal content -->
          <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
              <!-- Modal header -->
              <div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t dark:border-gray-600">
                  <h3 class="text-xl font-semibold text-gray-900 dark:text-white">
                      字段保存结果
                  </h3>
                  <button type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-hide="fieldLayoutModal">
                      <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
                          <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
                      </svg>
                      <span class="sr-only">Close modal</span>
                  </button>
              </div>
              <!-- Modal body -->
              <div class="p-4 md:p-5 space-y-4">
                <ul class="space-y-4 text-gray-500 list-disc list-inside dark:text-gray-400" id="fieldLayoutList">
                </ul>
              </div>
          </div>
      </div>
    </div>
    <builder-fiddle host="<%=builderHost%>"></builder-fiddle>
    <script>
      const useOpenAPI= <%=(useOpenAPI === "true" || useOpenAPI === true)%>;
      const settings = {
        assetUrls: "<%=assetUrls%>",
        rootUrl: "<%=rootUrl%>",
        userId: "<%=userId%>",
        tenantId: "<%=tenantId%>",
        authToken: "<%=authToken%>",
        pageId: "<%=pageId%>",
        messageOnly: true,
        useOpenAPI: useOpenAPI
      };

      let comp = document.querySelector("builder-fiddle");

      // set the modal menu element
      const $targetEl = document.getElementById('fieldLayoutModal');
      // options with default values
      const options = {
          placement: 'top-center',
          backdrop: 'dynamic',
          backdropClasses:
              'bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-40',
          closable: true,
          onHide: () => {
              console.log('modal is hidden');
          },
          onShow: () => {
              console.log('modal is shown');
          },
          onToggle: () => {
              console.log('modal has been toggled');
          },
      };
      // instance options object
      const instanceOptions = {
        id: 'fieldLayoutModal',
        override: true
      };
      const modal = new Flowbite.default.Modal($targetEl, options, instanceOptions);

      const loadPage = async () => {
        const { assetUrls, rootUrl, userId, tenantId, authToken, pageId } = settings;

        // 如果传入 steedos rooturl
        if (rootUrl && !authToken) return;

        const initialContent = {
          type: "page",
          title: "Welcome to Steedos",
          body: [],
          regions: ["body"],
          data: {
            objectName: "space_users",
            recordId: "",
            initialValues: {},
            appId: "builder",
            title: "",
            context: {
              rootUrl,
              userId,
              tenantId,
              authToken,
            },
          },
        };

        if (pageId) {
          const result = await axios.get(
            `${rootUrl}/service/api/page/pageVersion/${pageId}/latest/`,
            {
              withCredentials: true,
              headers: { Authorization: `Bearer ${tenantId},${authToken}` },
            }
          );
          if (result?.data) {
            let schema = result.data.schema || initialContent;

            let objectName = result.data.object_name;
            let pageType = result.data.type;
            if (typeof schema === "string") {
              schema = JSON.parse(schema);
            }

            if (!schema.data) {
              schema.data = {};
            }

            if (!schema.data.context) {
              schema.data.context = {};
            }

            schema.data.objectName = objectName;

            schema.data.context.rootUrl = rootUrl;
            schema.data.context.tenantId = tenantId;
            schema.data.context.userId = userId;
            schema.data.context.authToken = authToken;
            schema.data.context.user = <%- JSON.stringify(userSession) %>;

            if (objectName && pageType === "record") {
              const record = await axios.get(
                `${rootUrl}/api/v4/${objectName}?$orderby=modified&$top=1`,
                {
                  withCredentials: true,
                  headers: { Authorization: `Bearer ${tenantId},${authToken}` },
                }
              );
              const value = record?.data?.value;
              if (value?.length > 0) {
                schema.data.recordId = value[0]._id;
              }
            }

            return schema || initialContent
          }
        } else {
          return initialContent
        }
      };

      const savePage = async (data) => {
        const { rootUrl, userId, tenantId, authToken, pageId } = settings;

        if (!pageId) {
          return;
        }

        // 保存schema时,清理context下的认证信息
        const schema = JSON.parse(
          JSON.stringify(data.data.AmisSchema, null, 4)
        );
        if (schema.data && typeof schema.data.context === 'object' ) {
          delete schema.data.context
        }

        try {
          delete schema.data.recordId;
          delete schema.data.objectName;
        } catch (error) {
          
        }

        return await axios.put(
            `${rootUrl}/service/api/page/pageVersion/${pageId}`,
            {
              withCredentials: true,
              schema: JSON.stringify(schema, null, 4), //直接存储json格式会导致react form异常。
            },
            {
              headers: { Authorization: `Bearer ${tenantId},${authToken}` },
            }
          )
          .catch(function (error) {
            // handle error
            console.log(error);
          });
      };

      const getElement = (title,dataList) => {
        const topLevelLi = document.createElement('li');
        topLevelLi.textContent = title;
        
        const nestedUl = document.createElement('ul');
        nestedUl.classList.add('flex', 'flex-wrap', 'text-gray-900', 'dark:text-white');
        
        for (let i = 0; i < dataList.length; i++) {
          const nestedLi = document.createElement('li');
          nestedLi.classList.add('pl-6');
          nestedLi.textContent = dataList[i];
          nestedUl.appendChild(nestedLi);
        }
        
        topLevelLi.appendChild(nestedUl);
        return topLevelLi;
      }

      const convertLogToMessage = (fieldLayoutLog) => {
        var list = document.getElementById('fieldLayoutList');
        list.innerHTML = '';
        if (fieldLayoutLog.insert.success.length > 0) {
          const topLevelLi = getElement(`新增成功(${fieldLayoutLog.insert.success.length})`,fieldLayoutLog.insert.success);
          list.appendChild(topLevelLi);
        }
        if (fieldLayoutLog.insert.error.length > 0) {
          const topLevelLi = getElement(`新增失败(${fieldLayoutLog.insert.error.length})`,fieldLayoutLog.insert.error);
          list.appendChild(topLevelLi);
        }
        if (fieldLayoutLog.update.success.length > 0) {
          const topLevelLi = getElement(`修改成功(${fieldLayoutLog.update.success.length})`,fieldLayoutLog.update.success);
          list.appendChild(topLevelLi);
        }
        if (fieldLayoutLog.update.error.length > 0) {
          const topLevelLi = getElement(`修改失败(${fieldLayoutLog.update.error.length})`,fieldLayoutLog.update.error);
          list.appendChild(topLevelLi);
        }
        if (fieldLayoutLog.delete.success.length > 0) {
          const topLevelLi = getElement(`删除成功(${fieldLayoutLog.delete.success.length})`,fieldLayoutLog.delete.success);
          list.appendChild(topLevelLi);
        }
        if (fieldLayoutLog.delete.error.length > 0) {
          const topLevelLi = getElement(`删除失败(${fieldLayoutLog.delete.error.length})`,fieldLayoutLog.delete.error);
          list.appendChild(topLevelLi);
        }
      };

      const deployPageVersion = async () => {
        const { rootUrl, tenantId, authToken, pageId } = settings;

        if (!pageId) {
          return;
        }
        return axios
          .post(
            `${rootUrl}/service/api/page/deploy`,
            {
              withCredentials: true,
              pageId: pageId,
            },
            {
              headers: { Authorization: `Bearer ${tenantId},${authToken}` },
            }
          )
          .then(function (response) {
            //保存时, 刷新父页面
            if (window.opener) {
              window.opener.postMessage(
                Object.assign(
                  { type: "record.edited" },
                  { objectName: "pages" },
                  { record: {} }
                ),
                "*"
              );
            }
            if(response.data.fieldLayoutLog){
              convertLogToMessage(response.data.fieldLayoutLog);
              modal.show();
            }
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          });
      };
      window.addEventListener('message', function (event) {
        const { data } = event;
        if (data) {
          if (data.type === 'builder.loadContent') {
            loadPage().then((content)=>{
              comp.messageFrame('builder.contentChanged', { AmisSchema : content } )
            })
          }
          if (data.type === 'builder.saveContent') {
            savePage(data.data).then(()=>{
              comp.messageFrame('builder.contentSaved')
            })
          }
          if(data.type === "builder.deployContent"){
            deployPageVersion().then(()=>{
              comp.messageFrame('builder.contentDeployed')
            })
          }
        }
      })
    
      comp.settings = settings;
    </script>
  </body>
</html>
